#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <pthread.h>
#include <unistd.h>
using namespace std;

// 定义条件变量和锁
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int tickets = 10000;
void *GetTicket(void* args) {
    const char*  threadname = static_cast<const char*>(args);
    while (true) {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);
        if (tickets > 0) {
            printf("%s get a ticket: %d\n", threadname, tickets);
            tickets--;
            pthread_mutex_unlock(&mutex);
        } else {
            pthread_mutex_unlock(&mutex);
            break;
        }
    }
    return nullptr;
}

int main() {
    pthread_t t[3];

    const char* threadname1 = "thread-1";
    pthread_create(&t[0], nullptr, GetTicket, (void*)threadname1);

    const char* threadname2 = "thread-2";
    pthread_create(&t[1], nullptr, GetTicket, (void*)threadname2);

    const char* threadname3 = "thread-3";
    pthread_create(&t[2], nullptr, GetTicket, (void*)threadname3);

    while (true) {
        sleep(1);
        pthread_cond_signal(&cond);
    }


    pthread_join(t[0], nullptr);
    pthread_join(t[1], nullptr);
    pthread_join(t[2], nullptr);


    return 0;
}
